package com.dream.airinfo;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Instrumentation;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends Activity {

    private DBHelper dbHelper;
    private SQLiteDatabase dbRead,dbWrite;
    private WebView webView,webView_bottom,webView_right;
    private String clickCity;
    private List<int[]> cityXYList;
    private List<int[]> lineTypeXYList;
    private int cityXYIndex=0;
    private TextView tvAqi;
    private TextView tvPm25;
    private ImageView log;
    private TextView shcoolName;

    private static final int LOAD_MAP=0;
    private static final int LOAD_LINE=1;
    private static final int UPDATE_DATA=3;
    private static final int WURUAN_DATA=4;
    private static final int SET_SHCOOL=5;


    //数据更新时间，比如10点
    private static final int UPDATE_TIME=10;

    //城市列表
    private String[] citys;
    private String[] cityNames;
    private EditText editText;

    private Handler handler=new Handler(){

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                //加载图表
                case LOAD_MAP:
                    webView.loadUrl(getMapStr(cityNames));
                    webView_right.loadUrl(getRankStr(cityNames));
                    webView_bottom.loadUrl(getLineTableData("北京",7));
                    break;
                //点击事件
                case LOAD_LINE:
                    webView_right.loadUrl(getRankStr(cityNames));
                    webView_right.loadUrl(getTipStr(cityNames,clickCity));
                    webView_bottom.loadUrl(getLineTableData(clickCity,7));
                    break;
                case UPDATE_DATA:
                    getData();
                    break;
                case WURUAN_DATA:
                    tvAqi.setText("AQI："+msg.arg1);
                    tvPm25.setText("PM2.5："+(int)(msg.arg2-(Math.random()*10))+" μg/m3");
                    break;
                case SET_SHCOOL:
                    editText=new EditText(MainActivity.this);
                    new AlertDialog.Builder(MainActivity.this)
                            .setTitle("学校名称")
                            .setView(editText)
                            .setPositiveButton("保存", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    shcoolName.setText(editText.getText().toString());
                                }
                            })
                            .setNegativeButton("取消",null)
                            .show();
                    break;
            }
        }
    };

    private int clickNum=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        dbHelper=new DBHelper(this);
        dbRead=dbHelper.getReadableDatabase();
        dbWrite=dbHelper.getWritableDatabase();
        shcoolName= (TextView) findViewById(R.id.shcoolName);
        log = (ImageView) findViewById(R.id.log);
        log.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickNum++;
                if (clickNum==5){
                    clickNum=0;
                    handler.sendEmptyMessage(SET_SHCOOL);
                }
            }
        });
        initCity();
        initView1();
        initView2();
        initView3();
        getData();
        dateTimer();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                handler.sendEmptyMessage(LOAD_MAP);
            }
        },5000);
    }

    public void initCity(){
        tvAqi = (TextView) findViewById(R.id.tv_aqi);
        tvPm25 = (TextView) findViewById(R.id.tv_pm25);
        citys=new String[]{"beijing","shanghai","wuhan","chongqing","shenzhen"};
        cityNames=new String[]{"北京","上海","武汉","重庆","深圳"};
        cityXYList=new ArrayList<>();
        cityXYList.add(new int[]{1164,327});
        cityXYList.add(new int[]{1232,482});
        cityXYList.add(new int[]{1135,497});
        cityXYList.add(new int[]{1030,513});
        cityXYList.add(new int[]{1132,640});
        lineTypeXYList=new ArrayList<>();
        lineTypeXYList.add(new int[]{143,765});
        lineTypeXYList.add(new int[]{228,768});
    }


    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if(event.getKeyCode() == KeyEvent.KEYCODE_DPAD_UP && event.getAction() != KeyEvent.ACTION_UP) {
            if (cityXYIndex<=0){
                cityXYIndex=cityXYList.size()-1;
            }else{
                cityXYIndex--;
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Instrumentation instrumentation1=new Instrumentation();
                    instrumentation1.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(),MotionEvent.ACTION_DOWN,cityXYList.get(cityXYIndex)[0],cityXYList.get(cityXYIndex)[1],0));
                }
            }).start();
        }else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_DOWN && event.getAction() != KeyEvent.ACTION_UP){
            if (cityXYIndex>=cityXYList.size()-1){
                cityXYIndex=0;
            }else{
                cityXYIndex++;
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Instrumentation instrumentation2=new Instrumentation();
                    instrumentation2.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(),MotionEvent.ACTION_DOWN,cityXYList.get(cityXYIndex)[0],cityXYList.get(cityXYIndex)[1],0));
                }
            }).start();
        }else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_LEFT && event.getAction() != KeyEvent.ACTION_UP){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Instrumentation instrumentation2=new Instrumentation();
                    instrumentation2.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(),MotionEvent.ACTION_DOWN,lineTypeXYList.get(0)[0],lineTypeXYList.get(0)[1],0));
                    instrumentation2.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(),MotionEvent.ACTION_UP,lineTypeXYList.get(0)[0],lineTypeXYList.get(0)[1],0));
                }
            }).start();
        }else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_RIGHT && event.getAction() != KeyEvent.ACTION_UP){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Instrumentation instrumentation2=new Instrumentation();
                    instrumentation2.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(),MotionEvent.ACTION_DOWN,lineTypeXYList.get(1)[0],lineTypeXYList.get(1)[1],0));
                    instrumentation2.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(),MotionEvent.ACTION_UP,lineTypeXYList.get(1)[0],lineTypeXYList.get(1)[1],0));
                }
            }).start();
        }
        return true;
    }

    private Timer timer;

    public void dateTimer(){
        Calendar calendar=Calendar.getInstance();
        calendar.set(calendar.HOUR_OF_DAY,UPDATE_TIME);
        calendar.set(calendar.MINUTE,0);
        calendar.set(calendar.SECOND,0);
        Date time = calendar.getTime();
        if (time.before(new Date())){
            calendar.add(Calendar.DAY_OF_MONTH,1);
            time=calendar.getTime();
        }
        timer=new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(UPDATE_DATA);
            }
        },time,1000*60*60*24);
    }

    //初始化地图
    public void initView1(){
        webView = (WebView) findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setAllowFileAccess(true);
        webView.addJavascriptInterface(new JavaScriptInterface(this),"hello");
        webView.setWebChromeClient(new WebChromeClient());
        webView.setFocusable(false);
        webView.loadUrl("file:///android_asset/Test1.html");
    }
    //初始化图表
    public void initView2(){
        webView_bottom = (WebView) findViewById(R.id.webView_bottom);
        webView_bottom.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
        webView_bottom.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView_bottom.getSettings().setJavaScriptEnabled(true);
        webView_bottom.getSettings().setAllowFileAccess(true);
        webView_bottom.setWebChromeClient(new WebChromeClient());
        webView_bottom.setFocusable(false);
        webView_bottom.loadUrl("file:///android_asset/Test2.html");
    }
    //初始化排行榜
    public void initView3(){
        webView_right = (WebView) findViewById(R.id.webView_right);
        webView_right.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
        webView_right.getSettings().setJavaScriptEnabled(true);
        webView_right.getSettings().setAllowFileAccess(true);
        webView_right.setWebChromeClient(new WebChromeClient());
        webView_bottom.setFocusable(false);
        webView_right.loadUrl("file:///android_asset/Test3.html");
    }

    //地图JS调用Android接口
    class JavaScriptInterface{
        private Context context;

        public JavaScriptInterface(Context context) {
            this.context=context;
        }

        @JavascriptInterface
        public void showDataOnAndroid(String str){
            if(Arrays.asList(cityNames).contains(str)){
                clickCity=str;
                handler.sendEmptyMessage(LOAD_LINE);
            }
        }
    }

    //加载地图数据，数据来自PM2.5 IN网站
    public void getData(){
        if (isWifiConnected(this)){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    new GetHttpData(citys).getResult(new GetHttpData.OnFinshData() {
                        @Override
                        public void success(List<String[]> cityInfoList) {
                            for (int i = 0; i < cityInfoList.size(); i++) {
                                String[] info=cityInfoList.get(i);
                                String city=info[0];
                                String systime=formatDate();
                                //如果数据库不存在当天数据，则添加
                                if (!isExistData(city,systime)){
                                    dbWrite.execSQL("insert into AirInfo values(null,?,?,?,?)", new Object[]{city,info[1],info[2],systime});
                                }
                            }
                        }
                    });
                }
            }).start();
        }
    }

    //从SQLite数据库读取图表数据
    public String getLineTableData(String cityStr,int num){
        String str;
        String[] airDate_arr=new String[num];
        String[] aqi_arr=new String[num];
        String[] pm2_5_arr=new String[num];
        int index=airDate_arr.length-1;
        Cursor cursor = dbRead.rawQuery("select * from AirInfo where city=? order by _id desc limit 0,?",new String[]{cityStr,num+""});
        if (cursor!=null){
            while (cursor.moveToNext()){
                String airDate=cursor.getString(cursor.getColumnIndex("airDate"));
                String aqi=cursor.getString(cursor.getColumnIndex("aqi"));
                String pm2_5=cursor.getString(cursor.getColumnIndex("pm2_5"));
                airDate_arr[index]="\'"+airDate+"\'";
                aqi_arr[index]=aqi;
                pm2_5_arr[index]=pm2_5;
                index--;
            }
            cursor.close();
        }
        str="javascript:showLineData("+Arrays.toString(airDate_arr)+"," +Arrays.toString(aqi_arr)+","+Arrays.toString(pm2_5_arr)+")";
        return str;
    };

    public String getMapStr(String[] cityNames){
        String str="javascript:getData([";
        for (int i = 0; i < citys.length; i++) {
            Cursor cursor = dbRead.rawQuery("select * from AirInfo where city=? order by _id desc limit 1",new String[]{cityNames[i]});
            if (cursor!=null&&cursor.moveToNext()){
                String cityName=cursor.getString(cursor.getColumnIndex("city"));
                String aqi=cursor.getString(cursor.getColumnIndex("aqi"));
                String pm2_5=cursor.getString(cursor.getColumnIndex("pm2_5"));
                String[] arr={aqi,pm2_5,aqi,aqi,aqi,aqi,aqi,aqi};
                if (cityName.equals("武汉")){
                    Message message=new Message();
                    message.what=WURUAN_DATA;
                    message.arg1=Integer.parseInt(aqi);
                    message.arg2=Integer.parseInt(pm2_5);
                    handler.sendMessage(message);
                }
                if (i==citys.length-1){
                    str+="{name: '"+cityName+"', value: "+Arrays.toString(arr)+"}";
                }else {
                    str+="{name: '"+cityName+"', value: "+Arrays.toString(arr)+"},";
                }
            }
        }
        str+="])";
        return str;
    }

    public String getRankStr(String[] cityNames){
        String[] city_arr=new String[cityNames.length];
        String[] aqi_arr=new String[cityNames.length];
        String str;
        for (int i = 0; i < citys.length; i++) {
            Cursor cursor = dbRead.rawQuery("select * from AirInfo where city=? order by _id desc limit 1",new String[]{cityNames[i]});
            if (cursor!=null&&cursor.moveToNext()){
                String cityName=cursor.getString(cursor.getColumnIndex("city"));
                String aqi=cursor.getString(cursor.getColumnIndex("aqi"));
                city_arr[i]="\'"+cityName+"\'";
                aqi_arr[i]=aqi;
            }
        }
        str="javascript:setRankData("+Arrays.toString(city_arr)+","
                +Arrays.toString(aqi_arr)+ ")";
        System.out.println(str);
        return str;
    }

    public String getTipStr(String[] cityNames,String city){
        String str="";
        for (int i = 0; i < cityNames.length; i++) {
            if (cityNames[i].equals(city)){
                str="javascript:showTip("+i+")";
            }
        }
        return str;
    }

    //是否连接WIFI
    public static boolean isWifiConnected(Context context)
    {
        ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if(wifiNetworkInfo.isConnected())
        {
            return true ;
        }
        return false ;
    }

    //格式化时间
    public String formatDate(){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(new Date()).toString();
    };

    //判断数据库是否存在数据
    public boolean isExistData(String city,String dateStr){
        Cursor cursor = dbRead.rawQuery("select * from AirInfo where city=? and airDate=?",new String[]{city,dateStr});
        if (cursor.moveToNext()){
            cursor.close();
            return true;
        }
        cursor.close();
        return false;
    };

    @Override
    protected void onDestroy() {
        if (dbRead!=null){
            dbRead.close();
        }
        if (dbWrite!=null){
            dbWrite.close();
        }
        if (timer!=null){
            timer.cancel();
        }
        super.onDestroy();
    }
}
